#
# @lc app=leetcode.cn id=21 lang=python
#
# [21] 合并两个有序链表
#

# @lc code=start
# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


class Solution(object):
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        # 递归解法
        if l1 and l2:
            if l1.val > l2.val:
                l1, l2 = l2, l1     # 交换，让l1节点的值为小值
            l1.next = self.mergeTwoLists(l1.next, l2)
        return l1 or l2


class Solution(object):
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        # 交换解法：多个排序数组的排序，O(n)复杂度
        # 判断某一链表为空的情况
        if l1 is None:
            return l2
        if l2 is None:
            return l1

        result = ListNode()
        l3 = result

        while l1 and l2:
            if l1.val > l2.val:
                l1, l2 = l2, l1
            l3.next = l1
            l1 = l1.next
            l3 = l3.next

        if l1:
            l3.next = l1
        else:
            l3.next = l2
        
        return result.next

# @lc code=end

